﻿import React from 'react';
import ReactDOM from 'react-dom';
import mirror, {actions, connect} from 'mirrorx';
import { List, InputItem, WhiteSpace, WingBlank, Button,Picker,Flex,Modal,Checkbox} from 'antd-mobile';
import { createForm } from 'rc-form';

const ListItem = List.Item;
const CheckboxItem = Checkbox.CheckboxItem;
const AgreeItem = Checkbox.AgreeItem;

import { FormattedMessage} from 'react-intl';


if (!actions.bankcardInfo) {   
    mirror.model({
        name: 'bankcardInfo',
        initialState: {
           cardInfo:[]
        },
		 reducers: {
            setCardInfo(state,data){
                return Object.assign({}, state, {cardInfo:data});
            }
        },
        effects: {},
	})
}

class App extends React.Component { 
	constructor(props) {
		super(props);
		this.bankInfo = {};
		this.state={
			isAgree:false,
			errorMap:{},
			bank:'',
			province:[],
			city:[],
			isShow:true, //是否显示填写银行卡信息内容
			provinceList:[], //省json
			cityList:[]		//市json
		};

		const Lang = window.LangMessage ||{};

		// this.holder={
		// 	keycode:"holder",
		// 	text:"持卡人",
		// 	editable:false			
		// };
		this.cardNo={
			keycode:"cardNo",
			text:Lang.dcard_no || "卡号",
			type:"bankCard",
			required:true,
			tip:Lang.bankcard_no || "银行卡号",			
		};
		this.phone = [
			{
			name:"certificateNo",
			keycode:"certificateNo",
			text:Lang.bankcard_cert_no || "持卡人身份证号",
			type:"text",
			tip:Lang.input_bankcard_cert_no || "请输入持卡人身份证号",
			message:Lang.input_right_bankcard_cert_no || "请输入正确的身份证号",			
			required:true,  //默认是true
		},
			{
			name:"phone",
			keycode:"phone",
			text:Lang.phone_no || "手机号",
			type:"phone",
			tip:Lang.input_phone || "请输入手机号",
			message:Lang.input_correct_phone || "请输入正确的手机号",
			pattern:/[0-9\s]{13}/,
			required:true,  //默认是true
		}];
	}

	componentDidMount(){
		
		this.getJson('0'); //获取省的数据

		T.fetch({ //获取姓名
				url: "/customer/name.json",
				data: {},
			}).then((res) => {
				if (res.success) {
				this.setState({   
					holder:res.value
				})
				}
		});

    }

	getJson=(code)=>{  
		T.fetch({ //从后台获取省市的数据并重组数据
				url: "/tools/city/list.json",
				data: {"parentCode": code},
			}).then((res) => {
				if (res.success) {	
					let arr = res.value;
					let temp = [];	
					let obj = {};				
					for (var i = 0; i < arr.length; i++){
						obj = {
							label:arr[i].name,
							value:arr[i].code
						}
						temp.push(obj);
					}	
					if(code=='0'){
						this.setState({
							provinceList:temp
						})
					}else{
						this.setState({
							cityList:temp
						})
					}
				}
		});	
	}

	chooseProvince=(val)=>{
		this.setState({province:val})		
		this.getJson(val.toString());		
	}

	findBank=(e)=>{
		if(!e||e.length<=0)
		return;

		this.setState({
			cardNo:e
		})		
		T.fetch({ //获取所属银行 
				url: "/bank/card/info/"+T.trimAll(e)+".json",
				data: {},
			}).then((res) => {
				if (res.success) {
				this.bankInfo = res.value;
				console.log(this.bankInfo);
				if(!res.value||res.value.length<=0){
					T.showError("请输入正确的银行卡号");
					return;
				}
				this.setState({   
					bank:res.value.bankName
				});
				}
		});
	}

	onErrorClick=(keyCode)=>{	//点击报错icon出现的提示	
		const {getFieldError } = this.props.form;
		let msg = getFieldError(keyCode);
		if(msg){			
			T.showError(msg.join(","));
		}	
	}
	
	submit=()=>{
		const Lang = window.LangMessage ||{};
		this.props.form.validateFields((error, values) => {			
			var errorMap ={}
			if(error){
				for(var key in error){
					errorMap[key] = 1;
				}
			}else if(!this.state.isAgree){
				T.showError(Lang.confirm_agree_service_protcol || "请勾选同意服务协议");
			}			
			else{
			    values.holder = this.state.holder;
				values.cardNo = this.state.cardNo;
				values.bankCode = this.bankInfo.bankCode;
				values.phone = T.trimAll(values.phone);
				console.log(values);
				var infos = {};
				infos.provinceCode = this.state.province.toString();
				infos.cityCode = this.state.city.toString();
				var p = T.getAttrObject(this.state.provinceList,"value",infos.provinceCode)[0]				
				var c = T.getAttrObject(this.state.cityList,"value",infos.cityCode)[0];
				infos.provinceName = p.label;
				infos.cityName = c.label;
				infos.certificateNo = values.certificateNo;
				infos.mobileNo = values.phone;
				infos.bankType = "DEBITCARD";
				infos.userName = this.state.holder;
				infos.bankCode = this.bankInfo.bankCode;
				infos.cardNo = T.trimAll(this.state.cardNo);
				infos.bankName = this.bankInfo.bankName;
				console.log(infos);	
				// if(!T.check.idCard(values.ID)){
				// 	T.showInfo("请输入正确的身份证号");
				// 	return;
				// }
				T.fetch({ //身份证号、银行卡号、开户银行代码、手机号 校验是否绑定
				url: "/bank/card/info/verify.json",
				data: values,
				}).then((res) => {
					if (res.success) {
						if(res.value){
							actions.bankcardInfo.setCardInfo(infos);	
							actions.routing.push({
								pathname: 'bankcard-verify',
								search: '?phone=' + values.phone
							});
						}
					
				}
		   });

							
						
			}

			this.setState({
				errorMap
			});		
			console.log(error, values);
		});
	}

	next= () => {
		this.setState({ //点击下一步隐藏银行卡填写内容，显示下一步手机号验证信息
			isShow:false
		})
	}

	agree=()=>{
		this.setState({
			isAgree:!this.state.isAgree
		})
		console.log(this.state.isAgree);
	}

	render() {
		const { getFieldProps } = this.props.form;
		const cardNo = this.cardNo;	
		const provinceList = this.state.provinceList;
		const cityList = this.state.cityList;
		return (<div className="bankcard-manage">
			  <WhiteSpace/>
			  <WhiteSpace/>
			  {this.state.isShow &&				  
				  <div className="cardInfo">
					<InputItem 					
					value = {this.state.holder}
					editable={false}
					><FormattedMessage id='name' defaultMessage='姓名'/></InputItem>

					<InputItem 
					{...getFieldProps(cardNo.keycode,{
						rules: [{
							required: cardNo.required === undefined ? true:cardNo.required,
							message:cardNo.message,
							pattern:cardNo.pattern							
						}]
					})}
					type={cardNo.type}					
					extra={cardNo.extra}
					error ={this.state.errorMap[cardNo.keycode]}
					onErrorClick={this.onErrorClick.bind(this,cardNo.keycode)}
					clear
					placeholder={cardNo.tip}					
					editable={cardNo.editable}
					onBlur = {this.findBank.bind(this)}
					>{cardNo.text}</InputItem>
			  <WhiteSpace/>
			  <InputItem 					
					value = {this.state.bank}
					editable={false}
					><FormattedMessage id='belong_bank' defaultMessage='所属银行'/></InputItem>
			  <WhiteSpace/>
			  <List>				
				<Picker data={provinceList} cols={1} value={this.state.province} onChange={(value)=>this.chooseProvince(value)}>
					<ListItem arrow="horizontal"><FormattedMessage id='bank_in_province' defaultMessage='银行所在省'/></ListItem>
				</Picker>
				<Picker data={cityList} cols={1} value={this.state.city} onChange={(value)=>this.setState({city:value})}>
					<ListItem arrow="horizontal"><FormattedMessage id='bank_in_city' defaultMessage='银行所在市'/></ListItem>
				</Picker>
			  </List>
			  <WhiteSpace/>
			  <WhiteSpace/>
			  <WingBlank>	
			  <Button className="diy_background" type="primary" onClick={this.next}><FormattedMessage id='next' defaultMessage='下一步'/></Button>
			  </WingBlank>	
			  </div>
			}
			
			{!this.state.isShow &&
				<div className="telInfo">
				<List>
					{this.phone.map((item,index)=>
					<InputItem  key={index}
					{...getFieldProps(item.keycode,{
						rules: [{
							required: item.required === undefined ? true:item.required,
							message:item.message || (item.tip),
							pattern:item.pattern,
							name:item.name
						}]
					})}
					type={item.type}
					name={item.name}
					extra={item.extra}
					error ={this.state.errorMap[item.keycode]}
					onErrorClick={this.onErrorClick.bind(this,item.keycode)}
					clear
					placeholder={item.tip}
					labelNumber={7}
					>{item.text}</InputItem>			
					)}			
		        </List>
				<Flex>
					<Flex.Item>
					<AgreeItem data-seed="logId" onChange={this.agree}>
					<FormattedMessage id='agree' defaultMessage='同意'/><a onClick={(e) => { e.preventDefault(); alert('agree it'); }}><FormattedMessage id='user_service_protcol' defaultMessage='用户服务协议'/></a>
					</AgreeItem>
					</Flex.Item>
     		    </Flex>
				 <WhiteSpace/>
				 <WhiteSpace/>
				 <WingBlank>
				<Button className="diy_background" type="primary" onClick={this.submit}><FormattedMessage id='verify_info' defaultMessage='验证信息'/></Button>
				</WingBlank>	
				</div>
			
		    }
			  	
	  	</div>)
	}
}

const AppForm = createForm()(App);

export default connect(state => {
    return state.bankcardInfo;
  })(AppForm)